﻿using MyManager.Business;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace MyManager.Data
{
    internal class XMLHelper
    {

        internal static int serializeObjectToXML(Object objectToSerialize)
        {
            System.IO.FileStream fs = null;
            try
            {
                XmlSerializer xmlSer = new XmlSerializer(objectToSerialize.GetType());

                fs = new System.IO.FileStream(resolveFileName(objectToSerialize.GetType()), System.IO.FileMode.Create);
                xmlSer.Serialize(fs, objectToSerialize);
                fs.Close();
                return 1;
                
            }
            catch (Exception ex)
            {
                fs.Close();
                return -1;
            }
        }

        internal static T deserializeXMLToObject<T>()
        {

            System.IO.FileStream fs=null;
            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

                fs = new System.IO.FileStream(resolveFileName(typeof(T)),System.IO.FileMode.OpenOrCreate );
                Object objectTobeReturned = xmlSerializer.Deserialize(fs);
                fs.Close();
                return (T)objectTobeReturned;
                

            }
            catch (Exception ex)
            {
                fs.Close();
                return default(T);
            }
        }

        private static string resolveFileName(Type type)
        {

            switch (type.Name)

            {
                case "CategoryCollection" :
                    return @"D:\test\Category.xml";
                    
                case "TaskCollection":

                    return @"D:\test\Tasks.xml";
                
            }

            return null;
        }


        internal static string getUniqueId()
        {
            return Guid.NewGuid().ToString("N");
        }
    }
}
